package com.situ.mall.service.impl;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.mall.common.ServerResponse;
import com.situ.mall.dao.OrderItemMapper;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.entity.User;
import com.situ.mall.service.IOrderItemService;

@Service
public class OrderItemServiceImpl implements IOrderItemService{

	@Autowired
	private OrderItemMapper orderItemMapper;
	
	@Override
	public ServerResponse insertOrderItem(Long orderNo, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Integer userId = user.getId();
		List<Cart> carts = (List<Cart>) session.getAttribute("carts");
		System.out.println("carts=" + carts);
		OrderItem orderItem = new OrderItem();
		for (Cart cart : carts) {
			orderItem.setUserId(userId);
			orderItem.setOrderNo(orderNo);
			orderItem.setProductId(cart.getProductId());
			orderItem.setProductName(cart.getProduct().getName());
			orderItem.setProductImage(cart.getProduct().getMainImage());
			BigDecimal price = cart.getProduct().getPrice();
			orderItem.setCurrentUnitPrice(price);
			Integer quantity = cart.getQuantity();
			orderItem.setQuantity(quantity);
			BigDecimal quantityBigDecimal = new BigDecimal(quantity.toString());
			BigDecimal totalPrice = price.multiply(quantityBigDecimal);
			orderItem.setTotalPrice(totalPrice);
			
			int count = orderItemMapper.insert(orderItem);
			if (count != 1) {
				return ServerResponse.createSuccess("订单创建失败");
			}
		}
		return ServerResponse.createError("订单创建成功");
		
	}

	@Override
	public List<OrderItem> selectOrderItemByUserId(Integer userId) {
		return orderItemMapper.selectOrderItemByUserId(userId);
	}

}
